package utils;

import android.os.AsyncTask;

import com.ygk.bluepath.core.BActivity;
import com.ygk.bluepath.core.BPresenter;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import utils.ui.view.ProDialog_logo;

public class PostForPresenterUtil extends AsyncTask<Void, Integer, JSONObject> {

    String oid = "";
    List<NameValuePair> mparams = new ArrayList<NameValuePair>();
    String url = "";
    Object extraStr;
    BPresenter mPresenter;
    boolean canCancel = true;
    boolean showLoading = false;

    public PostForPresenterUtil(BPresenter mPresenter, String url,
                                HashMap<String, Object> map, boolean canCancel,
                                boolean showLoading, String oid, Object extraStr) {
        super();
        this.url = url.contains("http:") ? url : Inf.URLHEAD + url;
        this.mPresenter = mPresenter;
        this.canCancel = canCancel;
        this.showLoading = showLoading;
        this.oid = oid;
        this.extraStr = extraStr;

        JSONObject json = new JSONObject();
        try {
            Set<String> key_set = map.keySet();
            for (Iterator<String> it = key_set.iterator(); it.hasNext(); ) {
                String key = it.next();
                json.put(key, map.get(key).toString());

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("sign", json.toString()));
        this.mparams = params;
        LogUtils.i(url + "json_sent::" + params);

    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        if (!PhoneInformationUtil.isNetworkAvailable()) {
            if (mPresenter != null) {
                mPresenter.tt("网络未连接,请检查网络!");
                mPresenter.dealJsonObject(null, oid, extraStr);
            }

            return;
        }/*else if (IdouApp.getInstance().isMustToCheckUpdate()) {
            if (mPresenter != null) {
				mPresenter.checkUpdate();
				return;
			}
		}*/

        if (showLoading) {
            if (canCancel) {
                ProDialog_logo.show(mPresenter.getActivity(), true);
            } else {
                ProDialog_logo.show(mPresenter.getActivity(), false);
            }

        }

    }

    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();

        if (showLoading) {
            ProDialog_logo.close();
        }
        if (mPresenter != null) {
            mPresenter.dealJsonObject(null, oid, extraStr);
        }
    }

    protected void onPostExecute(JSONObject result) {
        ProDialog_logo.close();
        if (mPresenter != null) {
            mPresenter.dealJsonObject(result, oid, extraStr);
        }

    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        // TODO Auto-generated method stub

        JSONObject jsonObject = null;
        // instantiate HttpPost object from the url address

        HttpEntityEnclosingRequestBase httpRequest = new HttpPost(this.url);
        try {
            httpRequest
                    .setEntity(new UrlEncodedFormEntity(mparams, HTTP.UTF_8));
            // execute the post and get the response from servers
            HttpClient dhcClient = new DefaultHttpClient();
            dhcClient.getParams().setIntParameter(
                    HttpConnectionParams.SO_TIMEOUT, 15000); // 读取数据超时
            dhcClient.getParams().setIntParameter(
                    HttpConnectionParams.CONNECTION_TIMEOUT, 15000);// 连接超时

            HttpResponse httpResponse = dhcClient.execute(httpRequest);
            LogUtils.i("code::::::"
                    + httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // get the result
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                LogUtils.i(url + "-ResultString::" + strResult);
                jsonObject = new JSONObject(strResult);
            } else {
                LogUtils.i("Error Response:"
                        + httpResponse.getStatusLine().toString());
            }
        } catch (ConnectTimeoutException e) {
            // TODO: handle exception
            if (mPresenter != null) {
                mPresenter.tt("网络连接超时,请检查网络!");
            }
        } catch (SocketTimeoutException e) {
            // TODO: handle exception
            if (mPresenter != null) {
                mPresenter.tt("读取数据超时,请稍后重试!");
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;

    }

}
